<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ios," />





  <link rel="alternate" href="/atom.xml" title="搁浅丶岁月的变迁" type="application/atom+xml" />






<meta name="description" content="前言定时器的使用是软件开发基础技能，用于延时执行或重复执行某些方法。 我相信大部分人接触iOS的定时器都是从这段代码开始的: 1[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:YES] 但是你真的会用吗？ 正文iOS定时器首先来介绍iOS">
<meta name="keywords" content="ios">
<meta property="og:type" content="article">
<meta property="og:title" content="定时器 你真的会使用吗？">
<meta property="og:url" content="http://yoursite.com/2016/12/13/2016-12-13-定时器你真的会使用吗？/index.html">
<meta property="og:site_name" content="搁浅丶岁月的变迁">
<meta property="og:description" content="前言定时器的使用是软件开发基础技能，用于延时执行或重复执行某些方法。 我相信大部分人接触iOS的定时器都是从这段代码开始的: 1[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:YES] 但是你真的会用吗？ 正文iOS定时器首先来介绍iOS">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2178672-9de097ecc618b498.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-03-08T07:33:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="定时器 你真的会使用吗？">
<meta name="twitter:description" content="前言定时器的使用是软件开发基础技能，用于延时执行或重复执行某些方法。 我相信大部分人接触iOS的定时器都是从这段代码开始的: 1[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:YES] 但是你真的会用吗？ 正文iOS定时器首先来介绍iOS">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/2178672-9de097ecc618b498.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2016/12/13/2016-12-13-定时器你真的会使用吗？/"/>





  <title>定时器 你真的会使用吗？ | 搁浅丶岁月的变迁</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/liaoren512"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_red_aa0000.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">搁浅丶岁月的变迁</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">没有虽败犹荣，只有成王败寇。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2016/12/13/2016-12-13-定时器你真的会使用吗？/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="廖壬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/ichgo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="搁浅丶岁月的变迁">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">定时器 你真的会使用吗？</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-12-13T00:00:00+08:00">
                2016-12-13
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>定时器的使用是软件开发基础技能，用于延时执行或重复执行某些方法。</p>
<p>我相信大部分人接触iOS的定时器都是从这段代码开始的:</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="built_in">NSTimer</span> scheduledTimerWithTimeInterval:<span class="number">1.0</span> target:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(action:) userInfo:<span class="literal">nil</span> repeats:<span class="literal">YES</span>]</span><br></pre></td></tr></table></figure>
<p>但是你真的会用吗？</p>
<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><h2 id="iOS定时器"><a href="#iOS定时器" class="headerlink" title="iOS定时器"></a>iOS定时器</h2><p>首先来介绍iOS中的定时器</p>
<p>iOS中的定时器大致分为这几类：</p>
<ul>
<li><strong>NSTimer</strong></li>
<li><strong>CADisplayLink</strong></li>
<li><strong>GCD定时器</strong></li>
</ul>
<h3 id="NSTimer"><a href="#NSTimer" class="headerlink" title="NSTimer"></a>NSTimer</h3><h4 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h4><p><strong>NSTime</strong>定时器是我们比较常使用的定时器，比较常使用的方法有两种：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="built_in">NSTimer</span> *)timerWithTimeInterval:(<span class="built_in">NSTimeInterval</span>)ti target:(<span class="keyword">id</span>)aTarget selector:(SEL)aSelector userInfo:(<span class="keyword">nullable</span> <span class="keyword">id</span>)userInfo repeats:(<span class="built_in">BOOL</span>)yesOrNo;</span><br><span class="line"></span><br><span class="line">+ (<span class="built_in">NSTimer</span> *)scheduledTimerWithTimeInterval:(<span class="built_in">NSTimeInterval</span>)ti target:(<span class="keyword">id</span>)aTarget selector:(SEL)aSelector userInfo:(<span class="keyword">nullable</span> <span class="keyword">id</span>)userInfo repeats:(<span class="built_in">BOOL</span>)yesOrNo;</span><br></pre></td></tr></table></figure>
<p>这两种方法都是创建一个定时器，区别是用<code>timerWithTimeInterval:</code>方法创建的定时器需要手动加入RunLoop中。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建NSTimer对象</span></span><br><span class="line">NSTimer *timer = [NSTimer <span class="string">timerWithTimeInterval:</span><span class="number">3</span> <span class="string">target:</span>self <span class="string">selector:</span><span class="meta">@selector</span>(timerAction) <span class="string">userInfo:</span>nil <span class="string">repeats:</span>YES];</span><br><span class="line"><span class="comment">// 加入RunLoop中</span></span><br><span class="line">[[NSRunLoop mainRunLoop] <span class="string">addTimer:</span>timer <span class="string">forMode:</span>NSDefaultRunLoopMode];</span><br></pre></td></tr></table></figure>
<p>需要<strong>注意</strong>的是： <code>UIScrollView</code> 滑动时执行的是 <code>UITrackingRunLoopMode</code>，<code>NSDefaultRunLoopMode</code>被挂起，会导致定时器失效，等恢复为<strong>滑动结束</strong>时才恢复定时器。其原因可以查看我这篇<a href="http://www.jianshu.com/p/c4f552ceda63" target="_blank" rel="noopener">《Objective-C RunLoop 详解》</a>中的 “RunLoop 的 Mode“章节，有详细的介绍。</p>
<p>举个例子：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)startTimer&#123;</span><br><span class="line">    <span class="built_in">NSTimer</span> *<span class="built_in">UIScrollView</span> = [<span class="built_in">NSTimer</span> timerWithTimeInterval:<span class="number">0.5</span> target:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(action:) userInfo:<span class="literal">nil</span> repeats:<span class="literal">YES</span>];</span><br><span class="line">    [[<span class="built_in">NSRunLoop</span> mainRunLoop] addTimer:timer forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="keyword">void</span>)action:(<span class="built_in">NSTimer</span> *)sender &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"NSTimer: %d"</span>,i);</span><br><span class="line">    i++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>将<code>timer</code>添加到<strong>NSDefaultRunLoopMode</strong>中，没0.5秒打印一次，然后滑动<code>UIScrollView</code>.</p>
<p>打印台输出：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2178672-9de097ecc618b498.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>可以看出在滑动<code>UIScrollView</code>时，定时器被暂停了。</p>
<p>所以如果需要定时器在 <code>UIScrollView</code> 拖动时也不影响的话，有两种解决方法</p>
<ol>
<li><strong>timer</strong>分别添加到 <code>UITrackingRunLoopMode</code> 和 <code>NSDefaultRunLoopMode</code>中</li>
</ol>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[[<span class="built_in">NSRunLoop</span> mainRunLoop] addTimer:timer forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line">[[<span class="built_in">NSRunLoop</span> mainRunLoop] addTimer:timer forMode: <span class="built_in">UITrackingRunLoopMode</span>];</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>直接将<strong>timer</strong>添加到<code>NSRunLoopCommonModes</code> 中：</li>
</ol>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[[<span class="built_in">NSRunLoop</span> mainRunLoop] addTimer:timer forMode: <span class="built_in">NSRunLoopCommonModes</span>];</span><br></pre></td></tr></table></figure>
<p>但并不是都<strong>timer</strong>所有的需要在滑动<code>UIScrollView</code>时继续执行，比如使用<strong>NSTimer</strong>完成的帧动画，滑动<code>UIScrollView</code>时就可以停止帧动画，保证滑动的流程性。</p>
<p>若没有特殊要求的话，一般使用第二种方法创建完<strong>timer</strong>，会自动添加到<code>NSDefaultRunLoopMode</code>中去执行，也是平时最常用的方法。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">NSTimer *timer = [NSTimer <span class="string">scheduledTimerWithTimeInterval:</span><span class="number">1.0</span> <span class="string">target:</span>self <span class="string">selector:</span><span class="meta">@selector</span>(<span class="string">action:</span>) <span class="string">userInfo:</span>nil <span class="string">repeats:</span>YES];</span><br></pre></td></tr></table></figure>
<p>参数：</p>
<p><code>TimeInterval</code>：延时时间</p>
<p><code>target</code>:目标对象，一般就是<code>self</code>本身</p>
<p><code>selector</code>:执行方法</p>
<p><code>userInfo</code>:传入信息</p>
<p><code>repeats</code>:是否重复执行</p>
<p>以上创建的定时器，若<code>repeats</code>参数设为<code>NO</code>，执行一次后就会被释放掉;</p>
<p>若<code>repeats</code>参数设为<code>YES</code>重复执行时，必须手动关闭，否则定时器不会释放(停止）。</p>
<p>释放方法：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 停止定时器</span></span><br><span class="line">[<span class="meta">timer invalidate</span>];</span><br></pre></td></tr></table></figure>
<p>实际开发中，我们会将<code>NSTimer</code>对象设置为属性，这样方便释放。</p>
<p><strong>iOS10.0</strong> 推出了两个新的API，与上面的方法相比，<code>selector</code>换成Block回调以、减少传入的参数(那几个参数真是鸡肋)。不过开发中一般需要适配低版本，还是尽量使用上面的方法吧。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="selector-tag">NSTimer</span> *)<span class="selector-tag">timerWithTimeInterval</span><span class="selector-pseudo">:(NSTimeInterval)interval</span> <span class="selector-tag">repeats</span><span class="selector-pseudo">:(BOOL)repeats</span> <span class="selector-tag">block</span><span class="selector-pseudo">:(void</span> (^)(<span class="selector-tag">NSTimer</span> *<span class="selector-tag">timer</span>))<span class="selector-tag">block</span> <span class="selector-tag">API_AVAILABLE</span>(<span class="selector-tag">macosx</span>(10<span class="selector-class">.12</span>), <span class="selector-tag">ios</span>(10<span class="selector-class">.0</span>), <span class="selector-tag">watchos</span>(3<span class="selector-class">.0</span>), <span class="selector-tag">tvos</span>(10<span class="selector-class">.0</span>));</span><br><span class="line"></span><br><span class="line">+ (<span class="selector-tag">NSTimer</span> *)<span class="selector-tag">scheduledTimerWithTimeInterval</span><span class="selector-pseudo">:(NSTimeInterval)interval</span> <span class="selector-tag">repeats</span><span class="selector-pseudo">:(BOOL)repeats</span> <span class="selector-tag">block</span><span class="selector-pseudo">:(void</span> (^)(<span class="selector-tag">NSTimer</span> *<span class="selector-tag">timer</span>))<span class="selector-tag">block</span> <span class="selector-tag">API_AVAILABLE</span>(<span class="selector-tag">macosx</span>(10<span class="selector-class">.12</span>), <span class="selector-tag">ios</span>(10<span class="selector-class">.0</span>), <span class="selector-tag">watchos</span>(3<span class="selector-class">.0</span>), <span class="selector-tag">tvos</span>(10<span class="selector-class">.0</span>));</span><br></pre></td></tr></table></figure>
<p>###特点</p>
<ul>
<li><p><strong>必须加入Runloop</strong></p>
<p>  上面不管使用哪种方法，实际最后都会加入RunLoop中执行，区别就在于是否手动加入而已。</p>
</li>
<li><p><strong>存在延迟</strong></p>
<p>  不管是一次性的还是周期性的timer的实际触发事件的时间，都会与所加入的RunLoop和RunLoop Mode有关，如果此RunLoop正在执行一个连续性的运算，timer就会被延时出发。重复性的timer遇到这种情况，如果延迟超过了一个周期，则会在延时结束后立刻执行，并按照之前指定的周期继续执行，这个延迟时间大概为50-100毫秒.</p>
<p>  所以NSTimer不是绝对准确的,而且中间耗时或阻塞错过下一个点,那么下一个点就pass过去了.</p>
</li>
<li><p><strong>UIScrollView滑动会暂停计时</strong></p>
<p>  添加到<code>NSDefaultRunLoopMode</code>的 <code>timer</code> 在 <code>UIScrollView</code>滑动时会暂停，若不想被<code>UIScrollView</code>滑动影响，需要将 <code>timer</code> 添加再到 <code>UITrackingRunLoopMode</code> 或 直接添加到<code>NSRunLoopCommonModes</code> 中</p>
</li>
</ul>
<p>##CADisplayLink</p>
<p>CADisplayLink官方介绍：</p>
<blockquote>
<p>A CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display</p>
</blockquote>
<p><strong>CADisplayLink</strong>对象是一个和屏幕刷新率同步的定时器对象。每当屏幕显示内容刷新结束的时候，runloop就会向CADisplayLink指定的<code>target</code>发送一次指定的<code>selector</code>消息， CADisplayLink类对应的 <code>selector</code> 就会被调用一次。</p>
<p>从原理上可以看出，CADisplayLink适合做界面的不停重绘，比如视频播放的时候需要不停地获取下一帧用于界面渲染，或者做动画。</p>
<p>###使用方法</p>
<p>创建：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) <span class="built_in">CADisplayLink</span> *displayLink;</span><br><span class="line"></span><br><span class="line"><span class="keyword">self</span>.displayLink = [<span class="built_in">CADisplayLink</span> displayLinkWithTarget:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(handleDisplayLink:)];  </span><br><span class="line"></span><br><span class="line"><span class="comment">// 每隔1帧调用一次</span></span><br><span class="line"><span class="keyword">self</span>.displayLink.frameInterval = <span class="number">1</span>;  </span><br><span class="line"></span><br><span class="line">[<span class="keyword">self</span>.displayLink addToRunLoop:[<span class="built_in">NSRunLoop</span> currentRunLoop] forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br></pre></td></tr></table></figure>
<p>释放方法：</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">[self.displayLink invalidate];  </span><br><span class="line"></span><br><span class="line">self.displayLink = nil;</span><br><span class="line">```      </span><br><span class="line">当把**CADisplayLink**对象添加到runloop中后，`selector`就能被周期性调用，类似于重复的NSTimer被启动了；执行`invalidate`操作时，CADisplayLink对象就会从runloop中移除，`selector`调用也随即停止，类似于NSTimer的`invalidate`方法。</span><br><span class="line"></span><br><span class="line">**CADisplayLink**中有两个重要的属性：</span><br><span class="line"></span><br><span class="line">- **frameInterval**</span><br><span class="line"></span><br><span class="line">	NSInteger类型的值，用来设置间隔多少帧调用一次`selector`方法，默认值是<span class="number">1</span>，即每帧都调用一次。</span><br><span class="line">    </span><br><span class="line">- **duration**</span><br><span class="line"></span><br><span class="line">	`CFTimeInterval`值为`readOnly`，表示两次屏幕刷新之间的时间间隔。需要注意的是，该属性在`targe`t的`selector`被首次调用以后才会被赋值。`selector`的调用间隔时间计算方式是：**调用间隔时间 = duration × frameInterval**。</span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">###特点</span><br><span class="line"></span><br><span class="line">- **刷新频率固定**</span><br><span class="line">	</span><br><span class="line">	正常情况iOS设备的屏幕刷新频率是固定**<span class="number">60</span>Hz**,如果CPU过于繁忙，无法保证屏幕<span class="number">60</span>次/秒的刷新率，就会导致跳过若干次调用回调方法的机会，跳过次数取决CPU的忙碌程度。</span><br><span class="line">- **屏幕刷新时调用**</span><br><span class="line"></span><br><span class="line">	CADisplayLink在正常情况下会在每次刷新结束都被调用，精确度相当高。但如果调用的方法比较耗时，超过了屏幕刷新周期，就会导致跳过若干次回调调用机会	</span><br><span class="line"></span><br><span class="line">- **适合做界面渲染**</span><br><span class="line"></span><br><span class="line">	CADisplayLink可以确保系统渲染每一帧的时候我们的方法都被调用，从而保证了动画的流畅性。</span><br><span class="line"></span><br><span class="line">##GCD定时器</span><br><span class="line"></span><br><span class="line">**GCD定时器**和NSTimer是不一样的，NSTimer受RunLoop影响，但是GCD的定时器不受影响，因为通过源码可知RunLoop也是基于GCD的实现的，所以GCD定时器有非常高的精度。关于GCD的使用可一看看[这篇博客](http:<span class="comment">//www.cnblogs.com/pure/archive/2013/03/31/2977420.html)。</span></span><br><span class="line"></span><br><span class="line">###使用方法</span><br><span class="line">创建GCD定时器定时器的方法稍微比较复杂，看下面的代码：</span><br><span class="line"></span><br><span class="line">####单次的延时调用</span><br><span class="line">NSObject中的`performSelector:withObject:afterDelay:`以及 `performSelector:withObject:afterDelay:inModes:` 这两个方法在调用的时候会设置当前 runloop 中 `timer` ，前者设置的 `timer` 在 `NSDefaultRunLoopMode` 运行，后者则可以指定 **NSRunLoop** 的 `mode` 来执行。我们上面介绍过 runloop 中 `timer` 在 `UITrackingRunLoopMode` 被挂起，就导致了代码就会一直等待 `timer` 的调度,解决办法在上面也有说明。</span><br><span class="line"></span><br><span class="line">不过我们可以用另一套方案来解决这个问题，就是使用GCD中的 `dispatch_after` 来实现单次的延时调用：</span><br></pre></td></tr></table></figure>
<p>double delayInSeconds = 2.0;<br>    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));<br>    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){<br>        [self someMethod];<br>    });<br><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">####循环调用</span><br></pre></td></tr></table></figure></p>
<p>// 创建GCD定时器<br>dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);</p>
<p>dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);</p>
<p>dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行</p>
<p>// 事件回调<br>dispatch_source_set_event_handler(_timer, ^{</p>
<pre><code>dispatch_async(dispatch_get_main_queue(), ^{
    // 在主线程中实现需要的功能

}
</code></pre><p>}</p>
<p>});</p>
<p>// 开启定时器<br>dispatch_resume(_timer);</p>
<p>// 挂起定时器（dispatch_suspend 之后的 Timer，是不能被释放的！会引起崩溃）<br>dispatch_suspend(_timer);</p>
<p>// 关闭定时器<br>dispatch_source_cancel(_timer);</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">上面代码中要注意的是：</span><br><span class="line"></span><br><span class="line"><span class="number">1.</span> `dispatch_source_set_event_handler()`中的任务实在子线程中执行的，若需要回到主线程，要调用`dispatch_async(dispatch_get_main_queue(), ^&#123;&#125;`.</span><br><span class="line">- `dispatch_source_set_timer` 中第二个参数，当我们使用 `dispatch_time` 或者 `DISPATCH_TIME_NOW` 时，系统会使用默认时钟来进行计时。然而当系统休眠的时候，默认时钟是不走的，也就会导致计时器停止。使用 `dispatch_walltime ` 可以让计时器按照真实时间间隔进行计时.</span><br><span class="line">- 第三个参数， ` <span class="number">1.0</span> * NSEC_PER_SEC` 为每秒执行一次，对应的还有毫秒，分秒，纳秒可以选择.</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">- `dispatch_source_set_event_handler` 这个函数在执行完之后，block 会立马执行一遍，后面隔一定时间间隔再执行一次。而 `NSTimer` 第一次执行是到计时器触发之后。这也是和 `NSTimer` 之间的一个显著区别。</span><br><span class="line">- 挂起（暂停）定时器, `dispatch_suspend` 之后的 `Timer`，不能被释放的,会引起崩溃.</span><br><span class="line">- 创建的`timer`一定要有`dispatch_suspend(_timer)`或`dispatch_source_cancel(_timer)`这两句话来指定出口，否则定时器将不执行，若我们想无限循环可将 `dispatch_source_cancel(_timer)` 写在一句永不执行的`<span class="keyword">if</span>`判断语句中。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">##使用场景</span><br><span class="line"></span><br><span class="line">介绍完iOS中的各种定时器，接下来我们来说说这几种定时器在开发中的几种用法。</span><br><span class="line">###短信重发倒计时</span><br><span class="line"></span><br><span class="line">短信倒计时使我们登录注册常用的功能，一般设置为<span class="number">60</span>s，实现方法如下：</span><br></pre></td></tr></table></figure>
<p>// 计时时间<br>@property (nonatomic, assign) int timeout;</p>
<p>/*<em> 开启倒计时 </em>/</p>
<ul>
<li><p>(void)startCountdown {</p>
<p>  if (_timeout &gt; 0) {</p>
<pre><code>return;
</code></pre><p>  }</p>
<p>  _timeout = 60;</p>
<p>  // GCD定时器<br>  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);</p>
<p>  dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);</p>
<p>  dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行</p>
<p>  dispatch_source_set_event_handler(_timer, ^{</p>
<pre><code>if(_timeout &lt;= 0 ){// 倒计时结束

    // 关闭定时器
    dispatch_source_cancel(_timer);

    dispatch_async(dispatch_get_main_queue(), ^{

        //设置界面的按钮显示 根据自己需求设置
        [self.sendMsgBtn setTitle:@&quot;发送&quot; forState:UIControlStateNormal];

        self.sendMsgBtn.enabled = YES;

    });

}else{// 倒计时中

    // 显示倒计时结果

    NSString *strTime = [NSString stringWithFormat:@&quot;重发(%.2d)&quot;, _timeout];

    dispatch_async(dispatch_get_main_queue(), ^{

        //设置界面的按钮显示 根据自己需求设置

        [self.sendMsgBtn setTitle:[NSString stringWithFormat:@&quot;%@&quot;,strTime] forState:UIControlStateNormal];

        self.sendMsgBtn.enabled = NO;

    });

    _timeout--;
}
</code></pre><p>  });</p>
<p>  // 开启定时器<br>  dispatch_resume(_timer);</p>
</li>
</ul>
<p>}<br><figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">在上面代码中，我们设置了一个60s循环倒计时，当我们向服务器获取短信验证码成功时 调用该方法开始倒计时。每秒刷新按钮的倒计时数，倒计时结束时再将按钮 <span class="code">`Title`</span> 恢复为“发送”.</span><br><span class="line"></span><br><span class="line">有一点需要注意的是，按钮的样式要设置为 <span class="strong">**UIButtonTypeCustom**</span>,否则会出现刷新 <span class="code">`Title`</span> 时闪烁.</span><br><span class="line"></span><br><span class="line">我们可以把这个方法封装一下，方便调用，否则在控制器中写这么一大段代码确实也不优雅。</span><br><span class="line"></span><br><span class="line">效果如下：</span><br><span class="line"></span><br><span class="line">![](http://upload-images.jianshu.io/upload_images/2178672-3d4d1353bcc36026.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</span><br><span class="line"></span><br><span class="line"><span class="section">##### [代码链接](https://github.com/qiubaiying/BYTimer)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="section">###每个几分钟向服务器发送数据</span></span><br><span class="line"></span><br><span class="line">在有定位服务的APP中，我们需要每个一段时间将定位数据发送到服务器，比如每5s定位一次每隔5分钟将再统一将数据发送服务器，这样会处理比较省电。</span><br><span class="line">一般程序进入后台时，定时器会停止，但是在定位APP中，需要持续进行定位，APP在后台时依旧可以运行，所以在后台定时器也是可以运行的。</span><br><span class="line"></span><br><span class="line">注：关于iOS后台常驻,可以查看[<span class="string">这篇博客</span>](<span class="link">http://waitingyuan.blog.163.com/blog/static/2155781652014111133150534/</span>)</span><br><span class="line"></span><br><span class="line">在使用GCD定时的时候发现GCD定时器也可以在后代运行，创建方法同上面的短信倒计时.</span><br><span class="line"></span><br><span class="line">这里我们使用<span class="strong">**NSTimer**</span>来创建一个每个5分钟执行一次的定时器.</span><br></pre></td></tr></table></figure></p>
<p>#import &lt;Foundation/Foundation.h&gt;</p>
<p>typedef void(^TimerBlock)();</p>
<p>@interface BYTimer : NSObject</p>
<ul>
<li><p>(void)startTimerWithBlock:(TimerBlock)timerBlock;</p>
</li>
<li><p>(void)stopTimer;</p>
</li>
</ul>
<p>@end</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>#import “BYTimer.h”</p>
<p>@interface BYTimer ()</p>
<p>@property (nonatomic, strong) NSTimer *timer;<br>@property (nonatomic, strong) TimerBlock timerBlock;</p>
<p>@end</p>
<p>@implementation BYTimer</p>
<ul>
<li><p>(void)startTimerWithBlock:(TimerBlock)timerBlock {</p>
<p>   self.timer = [NSTimer timerWithTimeInterval:300 target:self selector:@selector(_timerAction) userInfo:nil repeats:YES];</p>
<p>  [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];<br>  _timerBlock = timerBlock;</p>
</li>
</ul>
<p>}</p>
<ul>
<li><p>(void)_timerAction {<br>  if (self.timerBlock) {</p>
<pre><code>self.timerBlock();
</code></pre><p>  }<br>}</p>
</li>
<li><p>(void)stopTimer {<br>  [self.timer invalidate];<br>}</p>
</li>
</ul>
<p>@end<br><code>`</code></p>
<p>该接口的实现很简单，就是 <strong>NSTimer</strong> 创建了一个300s执行一次的定时器，但是要注意定时器需要加入<code>NSRunLoopCommonModes</code>中。</p>
<p>要使定时器在后台能运行，app 就需要在 <a href="http://waitingyuan.blog.163.com/blog/static/2155781652014111133150534/" target="_blank" rel="noopener">后台常驻</a>。</p>
<h1 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h1><p>最后总结一下：</p>
<p>NSTimer 使用简单方便，但是应用条件有限。</p>
<p>CADisplayLink 刷新频率与屏幕帧数相同，用于绘制动画。具体使用可看我封装好的一个 <a href="https://github.com/qiubaiying/WaterRippleView" target="_blank" rel="noopener">水波纹动画</a>。</p>
<p>GCD定时器 精度高，可控性强，使用稍复杂。</p>

      
    </div>
    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <!--<a href="/tags/ios/" rel="tag"># ios</a>-->
            <a href="/tags/ios/" rel="tag"><i class="fa fa-tag"></i> ios</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/12/07/2016-12-07-忽略-Xcode8-中的注释警告⚠️/" rel="next" title="忽略 Xcode 8 中的注释警告">
                <i class="fa fa-chevron-left"></i> 忽略 Xcode 8 中的注释警告
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/12/21/2016-12-21-Objective-C-Category/" rel="prev" title="Objective-C：Category">
                Objective-C：Category <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/ichgo.jpg"
                alt="廖壬" />
            
              <p class="site-author-name" itemprop="name">廖壬</p>
              <p class="site-description motion-element" itemprop="description">Learn to choose, to forsake, to endure loneliness, to resist temptation.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">391</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">56</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liaoren512" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:liaoren512@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5281757990/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-globe"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-globe"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#正文"><span class="nav-number">2.</span> <span class="nav-text">正文</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#iOS定时器"><span class="nav-number">2.1.</span> <span class="nav-text">iOS定时器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#NSTimer"><span class="nav-number">2.1.1.</span> <span class="nav-text">NSTimer</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用方法"><span class="nav-number">2.1.1.1.</span> <span class="nav-text">使用方法</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#结语"><span class="nav-number">3.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<!--<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">廖壬</span>

  
</div>

<!-- 在网站底部加上访问量-->
<!--<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>-->
<!--pv的方式，单个用户连续点击n篇文章，记录n次访问量-->
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



-->
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>